# app/config.py
import os
import secrets  # 必须导入 secrets 模块
from dotenv import load_dotenv

# 先加载环境变量
load_dotenv()  # 自动从项目根目录加载.env文件

class Config:
    # 确保环境变量存在，或者生成安全的随机密钥
    SECRET_KEY = os.environ.get('SECRET_KEY')
    # 关闭事件系统以减少开销
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    # 启用跨域请求的凭证支持
    CORS_SUPPORTS_CREDENTIALS = True
    # 数据库配置 - 使用默认值
    DB_USER = os.getenv('DB_USER')
    DB_PASS = os.getenv('DB_PASS')
    DB_HOST = os.getenv('DB_HOST', 'localhost')
    DB_NAME = os.getenv('DB_NAME')
    SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{DB_USER}:{DB_PASS}@{DB_HOST}/{DB_NAME}"

    # 添加数据库连接池设置
    SQLALCHEMY_POOL_SIZE = 10
    SQLALCHEMY_POOL_TIMEOUT = 30
    SQLALCHEMY_POOL_RECYCLE = 1800  # 半小时

    # JWT配置
    JWT_SECRET_KEY = os.environ.get('JWT_SECRET_KEY') or SECRET_KEY  # 使用环境变量或SECRET_KEY
    JWT_ACCESS_TOKEN_EXPIRES = int(os.environ.get('JWT_ACCESS_TOKEN_EXPIRES', 36000))  # 10小

    BASE_URL = 'http://127.0.0.1:5000'
    UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), 'uploads')
    MAX_CONTENT_LENGTH = 100 * 1024 * 1024  # 100MB
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'doc', 'docx'}

    @property
    def SQLALCHEMY_DATABASE_URI(self):
        """动态生成数据库连接URI"""
        # 优先使用配置类中定义的数据库连接
        if hasattr(self, 'DB_CONFIG'):
            user = self.DB_CONFIG.get('DB_USER', os.getenv('DB_USER'))
            password = self.DB_CONFIG.get('DB_PASS', os.getenv('DB_PASS'))
            host = self.DB_CONFIG.get('DB_HOST', 'localhost')
            db_name = self.DB_CONFIG.get('DB_NAME', os.getenv('DB_NAME'))
            return f"mysql+pymysql://{user}:{password}@{host}/{db_name}"

        # 默认使用环境变量中的配置
        return os.environ.get(
            'DATABASE_URL') or f"mysql+pymysql://{os.getenv('DB_USER')}:{os.getenv('DB_PASS')}@localhost/{os.getenv('DB_NAME')}"


# 如果你有开发/生产环境配置，可以添加：
class DevelopmentConfig(Config):
    DEBUG = True
    # SQLALCHEMY_ECHO = True  # 打印SQL语句

    # 使用开发环境专有数据库配置
    DB_USER = os.getenv('DEV_DB_USER') or os.getenv('DB_USER')
    DB_PASS = os.getenv('DEV_DB_PASS') or os.getenv('DB_PASS')
    DB_NAME = os.getenv('DEV_DB_NAME') or os.getenv('DB_NAME')
    SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{DB_USER}:{DB_PASS}@localhost/{DB_NAME}"

    # 开发环境基本URL
    BASE_URL = 'http://127.0.0.1:5050'


class ProductionConfig(Config):
    DEBUG = False

    # 生产环境数据库配置
    DB_USER = os.getenv('PROD_DB_USER') or os.getenv('DB_USER')
    DB_PASS = os.getenv('PROD_DB_PASS') or os.getenv('DB_PASS')
    DB_HOST = os.getenv('PROD_DB_HOST') or os.getenv('DB_HOST', 'localhost')
    DB_NAME = os.getenv('PROD_DB_NAME') or os.getenv('DB_NAME')
    SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{DB_USER}:{DB_PASS}@{DB_HOST}/{DB_NAME}"

    # 生产环境基本URL
    BASE_URL = 'https://linkchatserver.xingkdsite.top'  # 替换为你的实际域名

    # 生产环境额外配置
    SQLALCHEMY_ENGINE_OPTIONS = {
        "pool_pre_ping": True,
        "pool_recycle": 1800,
    }